package com.clearliang.alarmnotice.view;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.clearliang.alarmnotice.bean.AlarmBean;
import com.clearliang.alarmnotice.utils.BasisTimesUtils;
import com.clearliang.alarmnotice.R;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ClearLiang on 2019/2/27
 * <p>
 * Function :
 */
public class EditDialogFragment extends DialogFragment {

    private EditText etName;
    private EditText etContent;
    private Button btnStartTime, btnEndTime;
    private Button btnOk, btnCancel;
    private TextView tvSelectMsg,tvSelect;

    private String stringTitle = "";
    private String stringContent = "";
    private String startTime = "08:00", endTime = "08:00";
    private List<String> stringWeekday;
    private OnResultListener onResultListener;

    private int hour,minute;
    private AlarmBean bean;

    public interface OnResultListener {
        void onTimeListener(String title, String content, String startTime, String endTime, List<String> weekday);
        void onTimeListener(AlarmBean alarmBean);
    }

    public void setOnResultListener(OnResultListener onResultListener) {
        this.onResultListener = onResultListener;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            onResultListener = (OnResultListener) getActivity();
        } catch (ClassCastException e) {
            throw new ClassCastException(getActivity().toString() + " must implements OnResultListener");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_setting, container);

        initData();
        initView(view);
        initEvent();

        return view;
    }

    // 接收item传来的数据
    private void initData() {
        stringWeekday = new ArrayList<>();
        Bundle bundle = getArguments();
        if (bundle != null) {
            String msg = bundle.getString("msg");
            //LogUtils.e("接收了",msg);
            bean = new AlarmBean();
            bean = JSON.parseObject(msg,AlarmBean.class);
            //LogUtils.e(JSON.toJSONString(bean));
        }
    }

    private void initEvent() {
        btnStartTime.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                hour = Integer.valueOf(btnStartTime.getText().toString().substring(0,2));
                minute = Integer.valueOf(btnStartTime.getText().toString().substring(3));
                showTimerPicker(btnStartTime,hour,minute);
            }
        });

        btnEndTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hour = Integer.valueOf(btnEndTime.getText().toString().substring(0,2));
                minute = Integer.valueOf(btnEndTime.getText().toString().substring(3));
                showTimerPicker(btnEndTime,hour,minute);
            }
        });

        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stringTitle = etName.getText().toString().trim();
                stringContent = etContent.getText().toString().trim();
                startTime = btnStartTime.getText().toString().trim();
                endTime = btnEndTime.getText().toString().trim();

                if (TextUtils.isEmpty(stringTitle)) {
                    ToastUtils.showLong("标题不可为空！");
                    return;
                }
                if (TextUtils.isEmpty(stringContent)) {
                    ToastUtils.showLong("内容不可为空！");
                    return;
                }
                if (TextUtils.isEmpty(startTime)) {
                    ToastUtils.showLong("时间不可为空！");
                    return;
                }
                if (TextUtils.isEmpty(endTime)) {
                    ToastUtils.showLong("时间不可为空！");
                    return;
                }
                if (stringWeekday.size()==0) {
                    ToastUtils.showLong("日期不可为空！");
                    return;
                }
                // 08:45 09:22
                if (Integer.valueOf(endTime.substring(0, 2)) < Integer.valueOf(startTime.substring(0, 2))) {
                    ToastUtils.showLong("结束时间必须大于起始时间");
                    return;
                } else if(endTime.substring(0, 2).equals(startTime.substring(0, 2))){
                    if (Integer.valueOf(endTime.substring(3)) < Integer.valueOf(startTime.substring(3))) {
                        ToastUtils.showLong("结束时间必须大于起始时间");
                        return;
                    }
                }
                if(bean!=null){
                    bean.setName(stringTitle);
                    bean.setContent(stringContent);
                    bean.setWeekday(stringWeekday);
                    bean.setStartTime(startTime);
                    bean.setEndTime(endTime);
                    onResultListener.onTimeListener(bean);
                }else {
                    onResultListener.onTimeListener(stringTitle, stringContent, startTime, endTime, stringWeekday);
                }
                dismiss();
            }
        });

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtils.showLong("取消了设置！");
                dismiss();
            }
        });

        tvSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showMultiChoiceDialog();
            }
        });

    }

    private void showMultiChoiceDialog() {
        final String[] items = new String[]{"周一", "周二", "周三", "周四", "周五", "周六","周日"};
        final QMUIDialog.MultiCheckableDialogBuilder builder = new QMUIDialog.MultiCheckableDialogBuilder(getActivity())
                //.setCheckedItems(new int[]{1, 3})
                .addItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
        builder.addAction("取消", new QMUIDialogAction.ActionListener() {
            @Override
            public void onClick(QMUIDialog dialog, int index) {
                dialog.dismiss();
            }
        });
        builder.addAction("提交", new QMUIDialogAction.ActionListener() {
            @Override
            public void onClick(QMUIDialog dialog, int index) {

                List<String> list = new ArrayList();
                for (int i = 0; i < builder.getCheckedItemIndexes().length; i++) {
                    //result += "" + items[builder.getCheckedItemIndexes()[i]];
                    list.add(items[builder.getCheckedItemIndexes()[i]]);
                }
                stringWeekday = list;
                StringBuffer stringBuffer = new StringBuffer();
                for(String a:stringWeekday){
                    stringBuffer.append(a).append("|");
                }
                tvSelectMsg.setText(stringBuffer);
                dialog.dismiss();
            }
        });
        builder.create(com.qmuiteam.qmui.R.style.QMUI_Dialog).show();
    }

    /**
     * 时间选择
     * @param button
     * @param hourOfDay
     * @param minuteOfHour
     */
    private void showTimerPicker(final Button button,int hourOfDay,int minuteOfHour) {
        BasisTimesUtils.showTimerPickerDialog(getActivity(), true, "请选择时间", hourOfDay, minuteOfHour, true, new BasisTimesUtils.OnTimerPickerListener() {
            @Override
            public void onConfirm(int hourOfDay, int minute) {
                String hours = String.valueOf(hourOfDay);
                String minutes = String.valueOf(minute);
                if (hourOfDay < 10) {
                    if (minute < 10) {
                        button.setText("0" + hours + ":" + "0" + minutes);//08:09
                    } else {
                        button.setText(hours + ":" + minutes);        //08:20
                    }
                } else {
                    if (minute < 10) {
                        button.setText(hours + ":" + "0" + minutes);    //12:09
                    } else {
                        button.setText(hours + ":" + minutes);        //12:20
                    }
                }

            }

            @Override
            public void onCancel() {
                button.setText("10:00");
            }
        });
    }

    private void initView(View view) {
        getDialog().setTitle("设置时间");
        etName = (EditText) view.findViewById(R.id.et_name);
        etContent = (EditText) view.findViewById(R.id.et_content);
        btnStartTime = (Button) view.findViewById(R.id.btn_start_time);
        btnEndTime = (Button) view.findViewById(R.id.btn_end_time);
        btnOk = (Button) view.findViewById(R.id.btn_ok);
        btnCancel = (Button) view.findViewById(R.id.btn_cancel);
        tvSelect = (TextView) view.findViewById(R.id.tv_select);
        tvSelectMsg = (TextView) view.findViewById(R.id.tv_select_msg);

        if(bean != null){
            etName.setText(bean.getName());
            etContent.setText(bean.getContent());
            btnStartTime.setText(bean.getStartTime().substring(0,5));
            btnEndTime.setText(bean.getEndTime().substring(0,5));
            stringWeekday = bean.getWeekday();
            StringBuffer stringBuffer = new StringBuffer();
            for(String a:stringWeekday){
                stringBuffer.append(a).append("|");
            }
            tvSelectMsg.setText(stringBuffer);
        }

    }


}
